package com.appkubes.mall.restful.application.utm.service.impl;

import com.appkubes.common.exception.BusinessException;
import com.appkubes.common.utils.net.IpUtils;
import com.appkubes.mall.core.entity.MallUserUtm;
import com.appkubes.mall.core.entity.MallUtmSource;
import com.appkubes.mall.core.service.impl.BaseMallUserUtmServiceImpl;
import com.appkubes.mall.restful.application.user.user.entity.vo.UserRegisterVO;
import com.appkubes.mall.restful.application.utm.service.UtmService;
import com.appkubes.mall.restful.application.utm.service.UtmSourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Rongjie
 * @Date: 2020/1/12 21:00
 * @Description:
 */
@Service
public class UtmServiceImpl extends BaseMallUserUtmServiceImpl implements UtmService {
    @Resource
    HttpServletRequest servletRequest;

    @Resource
    UtmSourceService utmSourceService;

    //用户注册
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Boolean register(String userKey, UserRegisterVO registerVO) throws BusinessException {
        MallUserUtm userUtm = getUserUtm(userKey); //获取用户的渠道信息
        BeanUtils.copyProperties(registerVO, userUtm);
        if (!StringUtils.isEmpty(registerVO.getUtmSource())) {
            MallUtmSource utmSource = utmSourceService.getUtmSource(registerVO.getUtmSource());
            if (utmSource != null) {
                //存在有效的渠道
                //记录注册来源信息
                userUtm.setUtmSource(registerVO.getUtmSource());
                utmSource.setCpa(utmSource.getCpa() + 1);
                utmSourceService.updateById(utmSource);
            }
        }
        this.saveOrUpdate(userUtm);
        return true;
    }

    MallUserUtm getUserUtm(String userKey) {
        MallUserUtm userUtm = this.getById(userKey);
        if (userUtm == null) {
            //补偿UTM数据
            userUtm = new MallUserUtm();
            userUtm.setUserKey(userKey);
            userUtm.setRegisterIp(IpUtils.getIpAddr(servletRequest));
            this.saveOrUpdate(userUtm);
        }
        return userUtm;
    }
}
